package com.mimosa.util.web;

import org.apache.commons.lang3.StringUtils;

import com.mimosa.util.constant.StringConstUtil;

/**
 * IP地址相关的类
 * 
 * @filename IPUtil.java
 * @author ggeale
 * @date 2014-8-2 下午9:15:40
 * 
 */
public final class IPUtil {
	/**
	 * 判断IP地址是否为本地地址
	 * 
	 * @param ip
	 * @return
	 */
	public static boolean isLocalAddr(String ip) {
		boolean result = false;
		if (StringUtils.equalsIgnoreCase(ip, "127.0.0.1") || StringUtils.equalsIgnoreCase(ip, "localhost")) {
			result = true;
		}
		return result;
	}

	/**
	 * 将IP地址转换为整型数字
	 * 
	 * @param ip
	 *            IP地址
	 * @return
	 */
	public static Long ipToLong(String ip) {
		Long result = 0l;
		if (StringUtils.isNotBlank(ip)) {
			String[] values = StringUtils.split(ip, StringConstUtil.DOT);
			if (values.length == 4) {
				for (String val : values) {
					result += Long.parseLong(val);
					result <<= 8;
				}
			}
		}
		return result;
	}

	/**
	 * 将整型数字转换成IP地址
	 * 
	 * @param ipnumber
	 *            数字形式的IP地址
	 * @return
	 */
	public static String longToIp(long ipaddress) {
		StringBuffer sb = new StringBuffer();
		sb.append(String.valueOf((ipaddress >>> 24)));
		sb.append(StringConstUtil.DOT);
		sb.append(String.valueOf((ipaddress & 0x00FFFFFF) >>> 16));
		sb.append(StringConstUtil.DOT);
		sb.append(String.valueOf((ipaddress & 0x0000FFFF) >>> 8));
		sb.append(StringConstUtil.DOT);
		sb.append(String.valueOf((ipaddress & 0x000000FF)));
		return sb.toString();
	}
}